﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SugarFineUI.Framework.Uitility;
using FineUIPro;

namespace SugarFineUI.CodeGenerator.Tool
{
    public partial class FiddlerRaw : FineUIPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                txa_SetHeaderValue.Text = @"
            /// <summary>
            ///  添加Host或Connection 的value值
            /// </summary>
            /// <param name=""header""></param>
            /// <param name=""name""></param>
            /// <param name=""value""></param>
            public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
            {
                var property = typeof(WebHeaderCollection).GetProperty(""InnerCollection"",
                    System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
                if (property != null)
                {
                    var collection = property.GetValue(header, null) as NameValueCollection;
                    collection[name] = value;
                }
            }" ;
            }
        }

        protected void btn_showCode_OnClick(object sender, EventArgs e)
        {
            #region raw报文
            /*
POST http://1024todo.cn/Admin/Login.aspx HTTP/1.1
Host: 1024todo.cn
Connection: keep-alive
Content-Length: 403
Origin: http://1024todo.cn
X-Requested-With: XMLHttpRequest
Cache-Control: no-cache
X-MicrosoftAjax: Delta=true
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Accept: *//*
Referer: http://1024todo.cn/Admin/Login.aspx
Accept - Encoding: gzip, deflate
Accept - Language: zh - CN,zh; q = 0.9
Cookie: Theme = Metro_Dark_Blue; Theme_Title = Metro % 20Dark % 20Blue

ScriptManager1 = UpdatePanel2 % 7CButton1 & __EVENTTARGET = &__EVENTARGUMENT = &__VIEWSTATE =% 2FwEPDwUJNzU4NjUzNzYzZGTZRG2FqoFuEup4GmR4Y2llrWeJ3VNm7YCEzKNPDMSpfQ % 3D % 3D & __EVENTVALIDATION =% 2FwEdAAQ5fagcKn357fZ4p3qZR014dxqY % 2BI5 % 2BIpdEa3UIFghPIFTr9jSm % 2BYRCsQXwbBZ9rtzN % 2BDvxnwFeFeJ9MIBWR6937X42Sik % 2FBSu9RlLCwJkhXOQuoer0yJ1ZcbK2 % 2BxS7JfY % 3D & tb_username = admin & tb_pwd = 123456 & __ASYNCPOST = true & Button1 =% E7 % 99 % BB % E5 % BD % 95
 */
            #endregion

            string info = txa_old.Text.Trim();
            string[] data = info.Split(Environment.NewLine.ToCharArray());
            if (data != null && data.Length > 0)
            {
                string post = data[0].Split(' ')[0];
                string url = data[0].Split(' ')[1];

                string Referer = string.Empty;
                string Host = string.Empty;
                string Connection = string.Empty;
                string User_Agent = string.Empty;
                string Content_Type = string.Empty;
                string Accept = string.Empty;
                string cookie = string.Empty;
                string charset = "utf-8";
                Dictionary<string, string> dataDic = new Dictionary<string, string>();
                Dictionary<string, string> headerDic = new Dictionary<string, string>();

                string key, value;
                string[] pars;
                string pKey, pValue;
                for (int i = 1; i < data.Length; i++)
                {
                    if (data[i].Length == 0) continue;
                    StringHelper.GetKeyAndValue(data[i], out key, out value, ":");
                    value = value.Trim();
                    switch (key)
                    {
                        case "Referer":
                            Referer = value;
                            break;
                        case "Host":
                            Host = value;
                            break;
                        case "Connection":
                            Connection = value;
                            break;
                        case "User-Agent":
                            User_Agent = value;
                            break;
                        case "Content-Type":
                            Content_Type = value;
                            if (value.Contains("charset="))
                            {
                                charset =
                                    value.Split(new string[] { "charset=" }, StringSplitOptions.None)[1].Split(';')[0];
                            }

                            break;
                        case "Accept":
                            Accept = value;
                            break;
                        case "Cookie":
                            cookie = value;
                            break;
                        case "Content-Length"://排除
                            break;
                        case "":
                            if (data[i].Contains("&")||data[i].Contains("=")||data[i].Length>0)
                            {
                                pars = data[i].Split('&');
                                for (int j = 0; j < pars.Length; j++)
                                {
                                    StringHelper.GetKeyAndValue(pars[j], out pKey, out pValue, "=");
                                    dataDic[pKey] = pValue;
                                }
                            }
                            break;
                        default://
                            headerDic[key] = value;
                            break;
                    }
                    //switch (key)
                    //{
                    //    case "Referer":
                    //        Referer = value;
                    //        continue;
                    //    case "Host":
                    //        Host = value;
                    //        continue;
                    //    case "Connection":
                    //        Connection = value;
                    //        continue;
                    //    case "User-Agent":
                    //        User_Agent = value;
                    //        continue;
                    //    case "Content-Type":
                    //        Content_Type = value;
                    //        continue;
                    //    case "Accept":
                    //        Accept = value;
                    //        continue;
                    //    case "Cookie":
                    //        cookie = value;
                    //        continue;
                    //    case "Content-Length"://排除
                    //        continue;
                    //    case "":
                    //        if (data[i].Contains("&"))
                    //        {
                    //            pars = data[i].Split('&');
                    //            for (int j = 0; j < pars.Length; j++)
                    //            {
                    //                StringHelper.GetKeyAndValue(pars[j], out pKey, out pValue, '=');
                    //                dataDic[pKey] = pValue;
                    //            }
                    //        }
                    //        continue;
                    //    default://
                    //           headerDic[key] = value;
                    //        continue;
                    //}
                }

                txa_new.Text = GetRawCode(post,
                    Referer,
                    Host,
                    Connection,
                    User_Agent,
                    Content_Type,
                    Accept,
                    cookie,
                    url,
                    charset,
                    dataDic, headerDic
                );
            }


        }

        private string GetRawCode(string POST,
                                       string Referer,
                                       string Host,
                                       string Connection,
                                       string User_Agent,
                                       string Content_Type,
                                       string Accept,
                                       string cookie,
                                       string url,
                                       string charset,
                                       Dictionary<string, string> dataDic,
                                       Dictionary<string, string> headerDic)
        {
            string headers = String.Empty;

            if (headerDic != null && headerDic.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (KeyValuePair<string, string> kv in headerDic)
                {
                    if (kv.Key != "Content-Length")//排除
                    {
                        sb.AppendLine(GetHeadersStr(kv.Key, kv.Value));
                    }
                }
                headers = sb.ToString();
            }

            string parData = string.Empty;
            if (dataDic != null && dataDic.Count > 0)
            {
                //ScriptManager1=UpdatePanel2%7CButton1&__EVENTTARGET=&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUJNzU4NjUzNzYzZGTZRG2FqoFuEup4GmR4Y2llrWeJ3VNm7YCEzKNPDMSpfQ%3D%3D&__EVENTVALIDATION=%2FwEdAAQ5fagcKn357fZ4p3qZR014dxqY%2BI5%2BIpdEa3UIFghPIFTr9jSm%2BYRCsQXwbBZ9rtzN%2BDvxnwFeFeJ9MIBWR6937X42Sik%2FBSu9RlLCwJkhXOQuoer0yJ1ZcbK2%2BxS7JfY%3D&tb_username=admin&tb_pwd=123456&__ASYNCPOST=true&Button1=%E7%99%BB%E5%BD%95
                bool isFrist = true;
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("                 StringBuilder sb = new StringBuilder();");
                foreach (KeyValuePair<string, string> kv in dataDic)
                {
                    //sb.Append("&ScriptManager1="+"UpdatePanel2%7CButton1");
                    if (isFrist)
                    {
                        sb.AppendLine("             sb.Append(\"" + kv.Key + "=\"+\"" + kv.Value + "\");");
                        isFrist = false;
                    }
                    else
                    {
                        sb.AppendLine("             sb.Append(\"&" + kv.Key + "=\"+\"" + kv.Value + "\");");
                    }
                }

                sb.AppendLine("             " + POST + "Data =sb.ToString();");
                parData = sb.ToString();
            }

            string codeStr = string.Empty;

            if (POST.Equals("Post", StringComparison.InvariantCultureIgnoreCase))
            {

                codeStr = $@"
            /// <summary>
            /// {POST}请求
            /// </summary>
            /// <returns></returns>
            public string Http{POST}()
            {{
                string {POST}URL=""{url}"";
                string {POST}Data= string.Empty;
                string cookie=""{cookie}"";

                {parData}

                try
                {{
                    //发送请求的数据
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create({POST}URL);
                    myHttpWebRequest.Method = ""{POST}"";

                    //headers相关
                    myHttpWebRequest.Accept = ""{Accept}"";
                    myHttpWebRequest.Referer = ""{Referer}"";
                    myHttpWebRequest.UserAgent =""{User_Agent}"";
                    myHttpWebRequest.ContentType = ""{Content_Type}"";
                    myHttpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;//自动解压缩 （gzip, deflate）
                    byte[] byte1 = Encoding.GetEncoding(""{charset}"").GetBytes({POST}Data);//注意编码格式
                    myHttpWebRequest.ContentLength = byte1.Length;

                    {headers}           
                    myHttpWebRequest.Headers.Add(""Cookie"", cookie);

                    SetHeaderValue(myHttpWebRequest.Headers, ""Host"", ""{Host}"");
                    SetHeaderValue(myHttpWebRequest.Headers, ""Connection"", ""{Connection}"");
                  
                    Stream newStream = myHttpWebRequest.GetRequestStream();
                    newStream.Write(byte1, 0, byte1.Length);
                    newStream.Close();

                    //发送成功后接收返回的信息
                    HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();
                    string lcHtml = string.Empty;
                    Encoding enc = Encoding.GetEncoding(""{charset}"");//注意编码格式
                    Stream stream = response.GetResponseStream();
                    StreamReader streamReader = new StreamReader(stream, enc);
                    lcHtml = streamReader.ReadToEnd();
                    return lcHtml;
                }}
                catch (Exception ex)
                {{
                    return ""{POST}异常:"" + ex.Message;
                }}
            }}
        
            " ;
            }
            else  //get 方式
            {
                codeStr = $@"
            /// <summary>
            /// {POST}请求
            /// </summary>
            /// <returns></returns>
            public string Http{POST}()
            {{
                string {POST}URL=""{url}"";
                string cookie=""{cookie}"";

                {parData}

                try
                {{
                    //发送请求的数据
                    HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create({POST}URL);
                    myHttpWebRequest.Method = ""{POST}"";

                    //headers相关
                    myHttpWebRequest.Accept = ""{Accept}"";
                    myHttpWebRequest.Referer = ""{Referer}"";
                    myHttpWebRequest.UserAgent =""{User_Agent}"";
                    myHttpWebRequest.ContentType = ""{Content_Type}"";
                    myHttpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;//自动解压缩 （gzip, deflate）
                  

                    {headers}           
                    myHttpWebRequest.Headers.Add(""Cookie"", cookie);

                    SetHeaderValue(myHttpWebRequest.Headers, ""Host"", ""{Host}"");
                    SetHeaderValue(myHttpWebRequest.Headers, ""Connection"", ""{Connection}"");                  
                 

                    //发送成功后接收返回的信息
                    HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();
                    string lcHtml = string.Empty;
                    Encoding enc = Encoding.GetEncoding(""{charset}"");//注意编码格式
                    Stream stream = response.GetResponseStream();
                    StreamReader streamReader = new StreamReader(stream, enc);
                    lcHtml = streamReader.ReadToEnd();
                    return lcHtml;
                }}
                catch (Exception ex)
                {{
                    return ""{POST}异常:"" + ex.Message;
                }}
            }}
        
            " ;
            }

            return codeStr;
        }

        private string GetHeadersStr(string key, string value)
        {
            return string.Format("                myHttpWebRequest.Headers.Add(\"{0}\",\"{1}\");", key, value);
        }
    }
}